package com.gjr.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.gjr.commonutils.Result;
import com.gjr.servicebase.exceptionhandler.GuliException;
import com.gjr.vod.service.VodService;
import com.gjr.vod.utils.ConstantVodUtils;
import com.gjr.vod.utils.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author 呙境仁
 * @create 2022-11-23 9:55
 */
@CrossOrigin
@RestController
@RequestMapping("/eduvod/video")
public class VodController {
    @Autowired
    private VodService vodService;

    /**
     * 上传视频到阿里云
     *
     * @param file 文件
     * @return 视频ID
     */
    @PostMapping("/uploadAlyVideo")
    public Result<?> uploadAlyVideo(MultipartFile file) throws IOException {
        // 返回上传视频的id值
        String videoId = vodService.uploadAlyVideo(file);

        if (videoId.isEmpty()) {
            return Result.error();
        } else {
            return Result.ok().data("videoId", videoId);
        }
    }

    /**
     * 根据视频id删除阿里云视频
     *
     * @param id 视频id
     * @return 返回值
     */
    @DeleteMapping("/removeAlyVideo/{id}")
    public Result<?> removeAlyVideo(@PathVariable String id) {

        try {
            // 初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            // 创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            // 向request设置视频id
            request.setVideoIds(id);
            // 调用初始化对象的方法实现删除
            client.getAcsResponse(request);

            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "删除视频失败");
        }
    }

    /**
     * 删除多个阿里云视频的方法
     *
     * @param videoIdList 视频id集合
     * @return 返回值
     */
    @DeleteMapping("/delete-batch")
    public Result<?> deleteBatch(@RequestBody List<String> videoIdList) {
        vodService.removeMoreAlyVideo(videoIdList);

        return Result.ok();
    }
}
